<?php
class CAuthItemTree extends CWidget{
	private $index = 0;
	/**
	 * Run this widget.
	 * This method registers necessary javascript and renders the needed HTML code.
	 */
	public $types = array('operation','task','role');
	public function run()
	{
		Yii::app()->clientScript->registerCoreScript('jquery.ui');
	 	$baseUrl = Yii::app()->baseUrl; 
	 	Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/modules/admin/components/'.__CLASS__.'/CAuthItemTree.js');
	  	Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/modules/admin/components/'.__CLASS__.'/CAuthItemTree.css');
		echo $this->renderHierachy('root');
	}
	/**
	 * This method return HTML for the tree
	 * Enter description here ...
	 * @param unknown_type $parent
	 * @param unknown_type $menuData
	 */
	public function buildTree($parent, $menuData)
	{
	    $html = '';
	
	    if (isset($menuData['parents'][$parent]))
	    {
	        if(!$this->index){
	    	$html = '<ul id="tag_tree" class="sf-menu sf-vertical">';
	        }else{
	        $html = '<ul>';
	        }
	        $index = 0;
	        foreach ($menuData['parents'][$parent] as $parentName)
	        {
	            //die(print_r($menuData['items'][$parentName]));
	        	
	        	$html .= '<li id="'.$parent.'_'.$menuData['items'][$parentName]->name.'" class="tree_item '.$this->types[$menuData['items'][$parentName]->type].'"><a href="#"><span>' . $menuData['items'][$parentName]->name.'</span></a>';
	            // find childitems recursively
	            $html .= $this->buildTree($parentName, $menuData);
	
	            $html .= '</li>';
	            $index++;
	        }
	        $html .= '</ul>';
	    }
		$this->index++;
	    return $html;
	}
	/**
	 * This method collect data from authManager and render the tree
	 * Enter description here ...
	 * @param unknown_type $root
	 */
	public function renderHierachy($root){
		$data = Yii::app()->authManager->getAuthItems();
		//die(print_r($data));
		$menuData = array(
		    'items' => $data,
		    'parents' => array()
		);
		foreach($data as $Item){
			if(count($children = array_keys($Item->getChildren()))){
				$menuData['parents'][$Item->name] = $children;	  
			} 
			if($Item->_parent == 'root'){
				$menuData['parents'][$Item->_parent][] = $Item->name;
			}
		}
		return $this->buildTree($root, $menuData);
	}
}